# -*- coding: utf-8 -*-
from www.shortcuts import *
from google.appengine.api import users
from google.appengine.ext import db
import random
import os
import csv


def get_word_ids():
    word_ids = cache.get("word_ids")
    if not word_ids:
        keys = db.GqlQuery("select __key__ from Word")
        word_ids = set(key.id() for key in keys)
    return word_ids


class Main(Handler):
    rule = Rule("/word/")
    def get(self):
        word_ids = get_word_ids()
        user = users.get_current_user()
        user_words = 0
        if user:
            user_id = user.user_id()
            key = "w-%s"%user_id
            words = cache.get(key)
            if words:
                word_ids = word_ids.difference(words)
                user_words = len(words)
        word_id = random.choice(list(word_ids))
        word = Word.get_by_id(word_id)
        tmpl = env.get_template("word.html")
        return Response(tmpl.render(
            word = word,
            users = users,
            user = user,
            request = self.request,
            flash_container = flash_container,
            word_number = len(word_ids),
            user_words = user_words,
        ))

    def post(self):
        user = users.get_current_user()
        response = redirect(self.request.url)
        if not user:
            return response
        word_id = int(self.request.form['word_id'])
        expect_word = self.request.form["expect_word"]
        if expect_word != self.request.form["word"]:
            flash(u"回答错误，正确答案是 %s"%expect_word, "error", response)
            return response
        user_id = user.user_id()
        key = "w-%s"%user_id
        words = cache.get(key, set())
        words.add(word_id)
        cache.set(key, words)
        flash(u"回答正确", response=response)
        return response


class Import(Handler):
    rule = Rule("/import/21/")
    def get(self):
        return Response("""
<html>
    <form method="post" action="." enctype="multipart/form-data">
        <input type="file" name="word-file" />
        <input type="submit" value="导入" />
    </form>
</html>
""")

    def post(self):
        word_file = self.request.files.get('word-file')
        csv_file = csv.reader(word_file)
        for row in csv_file:
            new_word = Word()
            new_word.word = row[1].decode("utf-8")
            new_word.paraphrase = row[2].decode("utf-8")
            new_word.sort_id = 1
            new_word.put()
        return Response("ok")


class Import(Handler):
    rule = Rule("/import/shucipiyi/")
    def get(self):
        return Response("""
<html>
    <form method="post" action="." enctype="multipart/form-data">
        <input type="file" name="word-file" />
        <input type="submit" value="导入" />
    </form>
</html>
""")

    def post(self):
        word_file = self.request.files.get('word-file')
        for line in word_file.readlines():
            line = line.decode("utf-8")
            x = line.split(None, 1)
            if len(x) != 2:
                continue
            word, paraphrase = x
            new_word = Word()
            new_word.word = word
            new_word.paraphrase = paraphrase
            new_word.sort_id = 2
            new_word.put()
        return Response("ok")
